package com.hqs.listener.fragment;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.hqs.listener.R;
import com.hqs.listener.activity.MainActivity;
import com.hqs.listener.adapter.FileListAdapter;
import com.hqs.listener.helper.Helper;
import com.hqs.listener.helper.HttpHelper;
import com.hqs.listener.model.FileModel;
import com.hqs.listener.model.ItemModel;
import com.hqs.listener.utils.FileUtil;
import com.lzy.okgo.model.Progress;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by super on 2017/11/13.
 */

public class FileListFragment extends BaseFragment {


    FileListAdapter adapter;


    @BindView(R.id.listView)
    ListView listView;

    @BindView(R.id.rl1)
    RelativeLayout relativeLayout;

    @BindView(R.id.progress)
    ProgressBar progressBar;

    @BindView(R.id.btnDownload)
    Button button;

    ArrayList<ItemModel> list = new ArrayList<>();
    MusicControlReceiver controlReceiver;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_filelist, null);
        ButterKnife.bind(this, view);
        setup();
        return view;
    }

    @Override
    public void didSetService() {
        super.didSetService();

        updateData();
        if (service.isDownloading()) {
            Helper.doInMainThread(new Runnable() {
                @Override
                public void run() {
                    downloadAction();
                }
            });
        }
    }

    void setup() {

        adapter = new FileListAdapter(getContext(), list);
        listView.setAdapter(adapter);

        relativeLayout.setVisibility(View.INVISIBLE);

        needDownloadFile(new Runnable() {
            @Override
            public void run() {
                relativeLayout.setVisibility(View.VISIBLE);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        downloadAction();
                    }
                });
            }
        });

        MainActivity.instance.titleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showChapters();
            }
        });
        setupTitle("创世纪");

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                for (ItemModel model : list) {
                    model.isPlaying = false;
                }
                list.get(i).isPlaying = true;
                adapter.notifyDataSetChanged();

                listView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        File file = new File(FileUtil.dataDir() + list.get(i).fullPath);
                        service.play(file);
                        service.setCurrentPlayIndex(i);
                    }
                }, 100);
            }
        });

        controlReceiver = new MusicControlReceiver();
        IntentFilter filter = new IntentFilter("music_action");
        getActivity().registerReceiver(controlReceiver, filter);
    }

    public void needDownloadFile(final Runnable task) {

        Helper.doInBackground(new Runnable() {
            @Override
            public void run() {
                String dir = FileUtil.dataDir();
                Realm realm = Realm.getDefaultInstance();
                RealmResults<FileModel> models = realm.where(FileModel.class).findAll();
                for (FileModel fileModel : models) {
                    File file = new File(dir + fileModel.fullPath);
                    if (file.exists() && fileModel.exists) {
                        continue;
                    } else {
                        Helper.doInMainThread(task);
                        return;
                    }
                }
            }
        });

    }

    public void showChapters() {
        final String[] chapters = service.getChapters();
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setItems(chapters, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                setupTitle(chapters[i]);
                updateData();
                service.setChapterIndex(i);
            }
        });
        builder.create().show();
    }

    public void setupTitle(String title) {
        MainActivity.instance.titleView.setText(title);
    }

    private void downloadAction() {

        if (service != null) {
            button.setEnabled(false);
            button.setText("正在准备下载...");
            service.downloadAll(new HttpHelper.DownloadFileListener() {
                @Override
                public void onProgress(Progress progress, String fileName) {
                    if (fileName.equals("completed")) {
                        Helper.doInMainThread(new Runnable() {
                            @Override
                            public void run() {
                                updateData();
                                relativeLayout.setVisibility(View.INVISIBLE);
                            }
                        });
                    } else {
                        updateDownload(progress, fileName);
                    }
                }
            });
        }
    }

    private void updateData() {

        Helper.doInMainThread(new Runnable() {
            @Override
            public void run() {
                list.clear();

                Realm realm = Realm.getDefaultInstance();
                RealmResults<FileModel> models = realm.where(FileModel.class).equalTo("path2", service.getChapter()).findAll();

                for (FileModel fileModel : models) {
                    ItemModel model = new ItemModel();
                    model.fileName = fileModel.fileName.substring(0, fileModel.fileName.length() - 4);
                    model.fullPath = fileModel.fullPath;
                    if (model.fileName.indexOf(service.getCurrentFileName()) >= 0 && service.getCurrentFileName().length() > 0){
                        model.isPlaying = true;
                    }
                    else {
                        model.isPlaying = false;
                    }
                    list.add(model);
                }

                adapter.notifyDataSetChanged();
                MainActivity.instance.titleView.setText(service.getChapter());
            }
        });
    }


    private void updateDownload(Progress progress, String fileName) {

        if (MainActivity.instance.viewPager.getCurrentItem() == 0) {
            fileName = fileName.substring(0, fileName.length() - 4);
            progressBar.setMax((int) progress.totalSize);
            progressBar.setProgress((int) progress.currentSize);
            button.setText(fileName + " " + FileUtil.fileSize(progress.currentSize) + "/" + FileUtil.fileSize(progress.totalSize));
        }
    }

    public class MusicControlReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getExtras().getString("msg");
            if (msg.equals("currentPlayingChanged")){
                updateData();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(controlReceiver);
    }
}
